package io.renren.modules.substation.controller;

import java.util.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.exception.RRException;
import io.renren.modules.substation.entity.*;
import io.renren.modules.substation.service.*;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.entity.SysMenuEntity;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.codec.binary.Base64;


/**
 * 监测区域信息表
 *
 * @author lan
 * @email sunlightcs@gmail.com
 * @date 2020-05-25 22:31:36
 */
@RestController
@RequestMapping("substation/tinfoareainfo")
public class TInfoAreaInfoController extends AbstractController {
    @Autowired
    private TInfoAreaInfoService tInfoAreaInfoService;
    @Autowired
    private TInfoDevInfoService tInfoDevInfoService;
    @Autowired
    private TInfoAlarmConfigService tInfoAlarmConfigService;
    @Autowired
    private TBusiSysAlarmInfoService tBusiSysAlarmInfoService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("substation:tinfoareainfo:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = tInfoAreaInfoService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{areaId}")
    @RequiresPermissions("substation:tinfoareainfo:info")
    public R info(@PathVariable("areaId") Long areaId){
        TInfoAreaInfoEntity tInfoAreaInfo = tInfoAreaInfoService.getById(areaId);

        return R.ok().put("tInfoAreaInfo", tInfoAreaInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("substation:tinfoareainfo:save")
    public R save(@RequestBody TInfoAreaInfoEntity tInfoAreaInfo){
        tInfoAreaInfo.setCreateOpr(getUserId());
        tInfoAreaInfoService.saveArea(tInfoAreaInfo);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("substation:tinfoareainfo:update")
    public R update(@RequestBody TInfoAreaInfoEntity tInfoAreaInfo){
//        TInfoAlarmConfigEntity s = tInfoAlarmConfigService.getCacheAlarmConfigInfo("3202140001-00湿度");
//        tInfoAlarmConfigService.updateHealthStatus("MP02MN6191231000038-00局放频次", "1");
//        tBusiSysAlarmInfoService.insertAlarmInfoBySystem("20200723121212", "MP02MN6191231000038", "00局放频次", "00局放频次");
        tInfoAreaInfo.setLastOpr(getUserId());
        tInfoAreaInfo.setLastTime(new Date());
        tInfoAreaInfoService.updateById(tInfoAreaInfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("substation:tinfoareainfo:delete")
    public R delete(@RequestBody Long[] areaIds){
        //删除区域前需判断该区域下有没有子区域
        for (Long areaId : areaIds){
            List<TInfoAreaInfoEntity> list = tInfoAreaInfoService.list(new QueryWrapper<TInfoAreaInfoEntity>()
                    .eq(areaId != null,"PARENT_AREA_CODE", areaId));
            if (list != null && list.size() > 0){
                TInfoAreaInfoEntity o = tInfoAreaInfoService.getById(areaId);
                return R.error("区域-" + o.getAreaName() + "下有子区域信息，请先删除其子区域信息");
            }
        }

//		tInfoAreaInfoService.removeByIds(Arrays.asList(areaIds));
        tInfoAreaInfoService.removeByIdAndRmoveDevInfo(areaIds, getUserId());

        return R.ok();
    }


    @RequestMapping("/areaNameDesc")
    @RequiresPermissions("substation:tinfoareainfo:areaNameDesc")
    public R areaNameDesc(){
        List<SelectItemInfo> list = new ArrayList<SelectItemInfo>();

        List<TInfoAreaInfoEntity> vlist = tInfoAreaInfoService.list();
        for (TInfoAreaInfoEntity o : vlist) {
            SelectItemInfo temp =new SelectItemInfo(o.getAreaName(), o.getAreaId() + "");
            list.add(temp);
        }
        return R.ok().put("list", list);
    }

    /**select
     * 区域选择菜单
     */
    @RequestMapping("/select")
    @RequiresPermissions("substation:tinfoareainfo:select")
    public R select(){
        //查询列表数据
        List<TInfoAreaInfoEntity> areaList = tInfoAreaInfoService.listByUserPerms();

        List<SysMenuEntity> menuList = new ArrayList<>();
        for(TInfoAreaInfoEntity o : areaList){
            SysMenuEntity m = new SysMenuEntity();
            m.setMenuId(o.getAreaId());
            m.setName(o.getAreaName());
            m.setType(Integer.parseInt(o.getAreaType()));
            m.setParentId(o.getParentAreaCode());
//            m.setOpen(true);
            menuList.add(m);
        }

        //添加顶级菜单
        SysMenuEntity root = new SysMenuEntity();
        root.setMenuId(0L);
        root.setName("测点区域");
        root.setParentId(-1L);
        root.setOpen(true);
        root.setType(0);
        menuList.add(root);

        return R.ok().put("menuList", menuList);
    }

    /**select_area_dev_list
     * 区域选择菜单
     */
    @RequestMapping("/select_area_dev_list")
    @RequiresPermissions("substation:tinfoareainfo:select_area_dev_list")
    public R selectAreaDevList(){
        logger.info("substation:tinfoareainfo:select_area_dev_list start...");
        //查询列表数据
        List<TInfoAreaInfoEntity> areaList = tInfoAreaInfoService.listByUserPerms();

        List<SysMenuEntity> menuList = new ArrayList<>();
        for(TInfoAreaInfoEntity o : areaList){
            SysMenuEntity m = new SysMenuEntity();
            m.setMenuId(o.getAreaId());
            m.setName(o.getAreaName());
            m.setType(Integer.parseInt(o.getAreaType()));
            m.setParentId(o.getParentAreaCode());
            m.setParentName(o.getParentName());
//            m.setOpen(true);
            menuList.add(m);
        }

        //添加顶级菜单
        SysMenuEntity root = new SysMenuEntity();
        root.setMenuId(0L);
        root.setName("测点区域");
        root.setParentId(-1L);
        root.setOpen(true);
        root.setType(0);
        menuList.add(root);

        //获取设备的所属区域信息
        Map<Long, List<SysMenuEntity>> devMap = new HashMap<>();
//        List<SysMenuEntity> list;
//        List<TInfoDevInfoEntity> devList = tInfoDevInfoService.list();
//        for(TInfoDevInfoEntity d : devList){
//            Long key = d.getDevArea();
//            if (key == null)
//                continue;
//            SysMenuEntity s = new SysMenuEntity();
//            s.setMenuId(d.getId());
//            s.setName(d.getDevName());
//            s.setParentId(d.getDevArea());
//            s.setOpen(true);
//            s.setType(9);
//            if (devMap.containsKey(key)){
//                list = devMap.get(key);
//            } else {
//                list = new ArrayList<>();
//            }f
//            list.add(s);
//            devMap.put(key, list);
//        }

        Map<String, Object> result = new HashMap<>();
        result.put("menuList", menuList);
        result.put("devMap", devMap);
        logger.info("substation:tinfoareainfo:select_area_dev_list end...");
        return R.ok().put("result", result);
    }

    /**select_area_dev_list
     * 区域选择菜单
     */
    @RequestMapping("/getAreaDevTree")
    @RequiresPermissions("substation:tinfoareainfo:getAreaDevTree")
    public R getAreaDevTree(){
        //查询列表数据
        List<TInfoAreaInfoEntity> areaList = tInfoAreaInfoService.listByUserPerms();

        List<SysMenuEntity> menuList = new ArrayList<>();
        for(TInfoAreaInfoEntity o : areaList){
            SysMenuEntity m = new SysMenuEntity();
            m.setMenuId(o.getAreaId());
            m.setName(o.getAreaName());
            m.setType(Integer.parseInt(o.getAreaType()));
            m.setParentId(o.getParentAreaCode());
//            m.setOpen(true);
            menuList.add(m);
        }

        //添加顶级菜单
        SysMenuEntity root = new SysMenuEntity();
        root.setMenuId(0L);
        root.setName("测点区域");
        root.setParentId(-1L);
        root.setOpen(true);
        root.setType(0);
        menuList.add(root);

        //获取设备的所属区域信息
        Map<Long, List<SysMenuEntity>> devMap = new HashMap<>();
        List<SysMenuEntity> list;
        List<TInfoDevInfoEntity> devList = tInfoDevInfoService.list();
        for(TInfoDevInfoEntity d : devList){
            Long key = d.getDevArea();
            if (key == null)
                continue;
            SysMenuEntity s = new SysMenuEntity();
            s.setMenuId(d.getId());
            s.setName(d.getDevName());
            s.setParentId(d.getDevArea());
            s.setOpen(true);
            s.setType(9);
            if (devMap.containsKey(key)){
                list = devMap.get(key);
            } else {
                list = new ArrayList<>();
            }
            list.add(s);
            devMap.put(key, list);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("menuList", menuList);
        result.put("devMap", devMap);
        return R.ok().put("result", result);
    }

    /** selectAreaListNoPerms
     * 观看区域选择菜单，此处必须加载完整的区域列表，即不带观看权限限制
     */
    @RequestMapping("/selectAreaListNoPerms")
    @RequiresPermissions("substation:tinfoareainfo:selectAreaListNoPerms")
    public R selectAreaListNoPerms(){
        //查询列表数据
        List<TInfoAreaInfoEntity> areaList = tInfoAreaInfoService.list();

        List<SysMenuEntity> menuList = new ArrayList<>();
        for(TInfoAreaInfoEntity o : areaList){
            SysMenuEntity m = new SysMenuEntity();
            m.setMenuId(o.getAreaId());
            m.setName(o.getAreaName());
            m.setType(Integer.parseInt(o.getAreaType()));
            m.setParentId(o.getParentAreaCode());
//            m.setOpen(true);
            menuList.add(m);
        }

        //添加顶级菜单
        SysMenuEntity root = new SysMenuEntity();
        root.setMenuId(0L);
        root.setName("测点区域");
        root.setParentId(-1L);
        root.setOpen(true);
        root.setType(0);
        menuList.add(root);

        //获取设备的所属区域信息
//        Map<Long, List<SysMenuEntity>> devMap = new HashMap<>();
//        List<SysMenuEntity> list;
//        List<TInfoDevInfoEntity> devList = tInfoDevInfoService.list();
//        for(TInfoDevInfoEntity d : devList){
//            Long key = d.getDevArea();
//            if (key == null)
//                continue;
//            SysMenuEntity s = new SysMenuEntity();
//            s.setMenuId(0L - d.getId());
//            s.setName(d.getDevName());
//            s.setParentId(d.getDevArea());
//            s.setOpen(true);
//            s.setType(9);
//            if (devMap.containsKey(key)){
//                list = devMap.get(key);
//            } else {
//                list = new ArrayList<>();
//            }
//            list.add(s);
//            devMap.put(key, list);
//        }

        Map<String, Object> result = new HashMap<>();
        result.put("menuList", menuList);
//        result.put("devMap", devMap);
        return R.ok().put("result", result);
    }

    /**
     * 选择区域所属下级区域,包括跨级的下级区域
     */
    @RequestMapping("/selectSubAreaById")
    public R selectSubAreaById(Long areaId){
        //查询列表数据
        TInfoAreaInfoEntity info = tInfoAreaInfoService.getById(areaId);
        if (info == null)
            return R.error("区域id" + areaId + "不存在");
        List<TInfoAreaInfoEntity> areaList = tInfoAreaInfoService.selectSubAreaById(areaId);

        List<SysMenuEntity> menuList = new ArrayList<>();
        for(TInfoAreaInfoEntity o : areaList){
            SysMenuEntity m = new SysMenuEntity();
            m.setMenuId(o.getAreaId());
            m.setName(o.getAreaName());
            m.setType(Integer.parseInt(o.getAreaType()));
            m.setParentId(o.getParentAreaCode());
//            m.setOpen(true);
            m.setType(Integer.parseInt(o.getAreaType()));
            menuList.add(m);
        }

//        //添加顶级菜单
//        SysMenuEntity root = new SysMenuEntity();
//        root.setMenuId(areaId);
//        root.setName(info.getAreaName());
//        root.setParentId((long)-1);
//        root.setOpen(true);
//        root.setType(Integer.parseInt(info.getAreaType()));
//        menuList.add(root);

        return R.ok().put("menuList", menuList);
    }

    /**selectonlyarea
     * 选择菜单(添加、修改菜单)
     */
    @RequestMapping("/selectonlyarea")
    @RequiresPermissions("substation:tinfoareainfo:selectonlyarea")
    public R selectonlyarea(){
        //查询列表数据
        List<TInfoAreaInfoEntity> areaList = tInfoAreaInfoService.queryOnlyAreaList();

        List<SysMenuEntity> menuList = new ArrayList<>();
        for(TInfoAreaInfoEntity o : areaList){
            SysMenuEntity m = new SysMenuEntity();
            m.setMenuId(o.getAreaId());
            m.setName(o.getAreaName());
            m.setType(Integer.parseInt(o.getAreaType()));
            m.setParentId(o.getParentAreaCode());
//            m.setOpen(true);
            m.setType(Integer.parseInt(o.getAreaType()));
            menuList.add(m);
        }

        //添加顶级菜单
        SysMenuEntity root = new SysMenuEntity();
        root.setMenuId(0L);
        root.setName("测点区域");
        root.setParentId(-1L);
        root.setOpen(true);
        root.setType(0);
        menuList.add(root);

        return R.ok().put("menuList", menuList);
    }

    /**selectOnlyAreaSta
     * 选择菜单(添加、修改菜单)
     */
    @RequestMapping("/selectOnlyAreaSta")
    @RequiresPermissions("substation:tinfoareainfo:selectOnlyAreaSta")
    public R selectOnlyAreaSta(){
        //查询列表数据
        List<TInfoAreaInfoEntity> areaList = tInfoAreaInfoService.queryOnlyAreaStaList();

        List<SysMenuEntity> menuList = new ArrayList<>();
        for(TInfoAreaInfoEntity o : areaList){
            SysMenuEntity m = new SysMenuEntity();
            m.setMenuId(o.getAreaId());
            m.setName(o.getAreaName());
            m.setType(Integer.parseInt(o.getAreaType()));
            m.setParentId(o.getParentAreaCode());
//            m.setOpen(true);
            m.setType(Integer.parseInt(o.getAreaType()));
            menuList.add(m);
        }

        //添加顶级菜单
        SysMenuEntity root = new SysMenuEntity();
        root.setMenuId(0L);
        root.setName("测点区域");
        root.setParentId(-1L);
        root.setOpen(true);
        root.setType(0);
        menuList.add(root);

        return R.ok().put("menuList", menuList);
    }

    /**
     * 配电房列表
     */
    @RequestMapping("/getAllAreaListByUser")
    @RequiresPermissions("substation:tinfoareainfo:getAllAreaListByUser")
    public R getAllAreaListByUser() {
        List<TInfoAreaInfoEntity> list = tInfoAreaInfoService.listByUserPerms();
        return R.ok().put("data", list);
    }

    /**
     * 配电房列表
     */
    @RequestMapping("/getStationList")
    @RequiresPermissions("substation:tinfoareainfo:getStationList")
    public R getStationList(){
        logger.info("substation:tinfoareainfo:getStationList start...");
//        List<TInfoAreaInfoEntity> list = tInfoAreaInfoService.getStationList();
        List<TInfoAreaInfoEntity> list = tInfoAreaInfoService.list();
        List<TInfoAreaInfoEntity> stationList = new ArrayList<>();
        Map<Long, TInfoAreaInfoEntity> areaMap = new HashMap<>();
        Map<Long, TInfoAreaInfoEntity> stationMap = new HashMap<>();
        int index = 0;
        int index3D = 0;
        for (TInfoAreaInfoEntity o : list){
            if (o.getAreaType().equals("1")){
                o.setIndex(index ++);
                if (o.getShowType() != null && o.getShowType().equals("1"))
                    o.setIndex3D(index3D ++);
                stationList.add(o);
                stationMap.put(o.getAreaId(),o);
            }
            if (o.getAreaImg() != null && !o.getAreaImg().equals(""))
                o.setAreaImg(getBase64Pic("jpg", o.getAreaImg()));
            areaMap.put(o.getAreaId(),o);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("areaInfoMap", areaMap);
        data.put("stationList", stationList);
        data.put("stationMap", stationMap);
        logger.info("substation:tinfoareainfo:getStationList end...");
        return R.ok().put("data", data);
    }

    public String getBase64Pic(String imgType, String imgStr){
        if(null == imgType || imgType.isEmpty()){
            return "";
        }
        if(imgType.equals("jpg")){
            imgType= "jpeg";
        }
        String pic_base64Info = "data:image/"+imgType+";base64," + imgStr;
//        logger.debug("pic_base64Info:"+ pic_base64Info);
        return pic_base64Info;
    }

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    @RequiresPermissions("substation:tinfoareainfo:upload")
    public R upload(@RequestParam("file") MultipartFile file, Long areaId) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        //上传文件
        byte[] imgByte = file.getBytes();
        String base64 = Base64.encodeBase64String(imgByte);
//        String base64 = new BASE64Encoder().encode(imgByte);
        //保存文件信息
        TInfoAreaInfoEntity info = new TInfoAreaInfoEntity();
        info.setAreaId(areaId);
        info.setAreaImg(base64);
        info.setLastOpr(getUserId());
        info.setLastTime(new Date());
        tInfoAreaInfoService.updateById(info);
        return R.ok();
    }

}
